import React, {Fragment} from 'react';
import {Form, Input, Row, Col, Checkbox, Button, message} from 'antd';
import logo from '@/assets/img/DLUTBadge.webp'
import './forgetPassword.less'
import memoryUtils from "../../utils/memoryUtils";
import storageUtils from "../../utils/storageUtils";
import {reqCode, reqRegister} from '../../api'
import Validation from "../Validation/Validation";
import checkEmail from "../../utils/checkEmail";
import {Redirect} from "react-router-dom";
import {LockOutlined} from "@ant-design/icons";

//添加 发送邮箱 验证功能

// import HCaptcha from '@hcaptcha/react-hcaptcha';


const formItemLayout = {
    labelCol: {
        xs: {span: 24},
        sm: {span: 8},
    },
    wrapperCol: {
        xs: {span: 24},
        sm: {span: 16},
    },
};

const tailFormItemLayout = {
    wrapperCol: {
        xs: {
            span: 24,
            offset: 0,
        },
        sm: {
            span: 16,
            offset: 8,
        },
    },
};

interface user {
    name: string,
    password: string,
    email: string,
    student_id?: string,
    verify_code?: string,
}


function ForgetPassword() {

    const [form] = Form.useForm();

    const [info, setInfo] = React.useState({
        currentIndex: 1,    // 忘记密码当前处于第几步
        email: '',
        name: '',
        codeLoading: false,
        codeText: '获取验证码',
        disabled: true
    })


    const onFinish = async (values: any) => {

        if (info.currentIndex === 1) {
            const {name, email} = values
            setInfo({disabled: true, codeLoading: false, codeText: '获取验证码', currentIndex: 1, name, email})
            if (!name || !email) {
                message.error("请输入账号或者邮箱必须验证！")
                return;
            }

            if (await checkEmail({name, email})) {
                message.success('验证成功！');

                setInfo({disabled: true, codeLoading: false, codeText: '获取验证码', currentIndex: 2, name, email})
            } else {
                message.error("请输入正确的用户名和邮箱！")
                return;
            }

        } else {
            const {password} = values
            const user: user = {name: info.name, password, email: info.email}
            const result = await reqRegister(user)

            if (result.status === 200) {
                message.success('更改密码成功！');
                const user = result.data;
                memoryUtils.user = user;
                storageUtils.saveUser(user);
                return <Redirect to={'/login'}/>
            }
        }


    };

    const countDown = () => {
        let sec = 60
        const {name, email} = info

        setInfo({disabled: true, codeLoading: false, codeText: `${sec}s`, currentIndex: 1, name, email})

        let timer = setInterval(() => {
            sec--;
            if (sec < 0) {
                setInfo({disabled: false, codeLoading: false, codeText: `重新获取`, currentIndex: 1, name, email})
                clearInterval(timer)
                return;
            }
            setInfo({disabled: true, codeLoading: false, codeText: `${sec}s`, currentIndex: 1, name, email})

        }, 1000)
    }

    const getCode = () => {
        const {name, email} = info

        setInfo({disabled: true, codeLoading: true, codeText: '发送中', currentIndex: 1, name, email})

        reqCode(info.email).then((response) => {
            //执行倒计时函数
            countDown()


            return;
        })

        setInfo({disabled: false, codeLoading: false, codeText: '重新发送', currentIndex: 1, name, email})

    }

    const handleInput = (e: any) => {
        if ((/^([a-zA-Z]|[0-9])(\w|-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/.test(e.target.value))) {
            setInfo({
                codeLoading: false,
                codeText: '获取验证码',
                currentIndex: 1,
                name: info.name,
                email: e.target.value,
                disabled: false
            })

        }
    }


    return (
        <div className={"forget"}>

            <header className={'forget-header'}>
                <img src={logo} alt="DLUT badge"/>
                <h1>OurEDA 网盘获取新密码</h1>
            </header>

            <div className={'forget-content'}>
                <h2>获取新密码！</h2>
                <Form
                    {...formItemLayout}
                    form={form}
                    name="forget"
                    onFinish={onFinish}
                    scrollToFirstError
                >

                    {
                        info.currentIndex === 1
                            ?
                            <Fragment>
                                <Form.Item
                                    name="name"
                                    label="Nickname"
                                    tooltip="Your nickname"
                                    rules={[
                                        {required: true, message: 'Please input your nickname!', whitespace: true}
                                    ]}
                                >
                                    <Input placeholder="Nickname"/>
                                </Form.Item>

                                <Form.Item
                                    name="email"
                                    label="E-mail"
                                    tooltip="Please input your email "
                                    rules={[
                                        {
                                            type: 'email',
                                            message: 'The input is not valid E-mail!',
                                        },
                                        {
                                            required: true,
                                            message: 'Please input your E-mail!',
                                        },
                                        {
                                            pattern: /^([a-zA-Z]|[0-9])(\w|-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/,
                                            message: '请输入正确的邮箱'
                                        }
                                    ]}
                                >
                                    <Input value={info.email} onChange={handleInput} placeholder=" E-mail"/>
                                </Form.Item>

                                <Form.Item
                                    name="code"
                                    label="Code"
                                    tooltip="Your get code"
                                    rules={[
                                        {required: true, message: 'Please input your Code!', whitespace: true}
                                    ]}
                                >
                                    <Row gutter={30}>
                                        <Col span={13}>
                                            <Input prefix={<LockOutlined className="site-form-item-icon"/>}
                                                   type="password" placeholder=" Code"/>
                                        </Col>
                                        <Col span={1}>
                                            <Button loading={info.codeLoading} type={'primary'} onClick={getCode}
                                                    disabled={info.disabled}>{info.codeText}</Button>
                                        </Col>
                                    </Row>
                                </Form.Item>


                                <Form.Item {...tailFormItemLayout}>
                                    <Button type="primary" htmlType="submit">
                                        Confirm!
                                    </Button>
                                </Form.Item>

                            </Fragment>
                            :
                            <Fragment>
                                <Form.Item
                                    name="password"
                                    label={'password'}
                                    rules={[
                                        {type: "string", required: true, whitespace: true, message: '密码必须输入!'},
                                        {max: 15, message: '最多为15位!'},
                                        {min: 8, message: '最少为8位!'},
                                        {pattern: /^[a-zA-Z0-9]{8,15}$/, message: '请输入正确的密码!'},
                                    ]}
                                    hasFeedback
                                    tooltip="The password consists of letters and numbers. The maximum value is 15  Bits, minimum 8 bits  "
                                >
                                    <Input.Password/>
                                </Form.Item>
                                <Form.Item
                                    name="confirm"
                                    label="Confirm Password"
                                    dependencies={['password']}
                                    hasFeedback
                                    tooltip="Please enter your password again to confirm"
                                    rules={[
                                        {
                                            required: true,
                                            message: 'Please confirm your password!',
                                        },
                                        ({getFieldValue}) => ({
                                            validator(_, value) {
                                                if (!value || getFieldValue('password') === value) {
                                                    return Promise.resolve();
                                                }
                                                return Promise.reject(new Error('The two passwords that you entered do not match!'));
                                            },
                                        }),
                                    ]}
                                >
                                    <Input.Password/>
                                </Form.Item>

                                <Form.Item
                                    label="Captcha">
                                    <Row gutter={8}>
                                        <Col span={12}>
                                            <Form.Item
                                                name="captcha"
                                                noStyle
                                                rules={[
                                                    {required: true, message: 'Please input the captcha you got!'},
                                                    () => ({
                                                        validator(_, value) {
                                                            console.log(memoryUtils.result.join(''), value)
                                                            if (memoryUtils.result.join('') === value) {
                                                                return Promise.resolve();
                                                            }
                                                            return Promise.reject(new Error('验证码错误！'));
                                                        },
                                                    }),
                                                ]}
                                            >
                                                <Input/>
                                            </Form.Item>
                                        </Col>

                                        <Validation/>
                                    </Row>

                                </Form.Item>

                                <Form.Item
                                    name="agreement"
                                    valuePropName="checked"
                                    rules={[
                                        {
                                            validator: (_, value) =>
                                                value ? Promise.resolve() : Promise.reject(new Error('Should accept agreement')),
                                        },
                                    ]}
                                    {...tailFormItemLayout}
                                >
                                    <Checkbox>
                                        I have read the <a href="">agreement</a>
                                    </Checkbox>
                                </Form.Item>

                                {/*<HCaptcha*/}
                                {/*    sitekey="7ce7c5df-08d2-4881-a4fc-6e4ac500706a"*/}
                                {/*    onVerify={(token)=>{*/}
                                {/*        console.log("token:",token)*/}
                                {/*    }}*/}
                                {/*/>*/}

                                <Form.Item {...tailFormItemLayout}>
                                    <Button type="primary" htmlType="submit">
                                        Find password!
                                    </Button>
                                </Form.Item>

                            </Fragment>

                    }

                </Form>
            </div>

        </div>
    );

}

export default ForgetPassword;